// pages/group_join/group_join.js
const app = getApp()
const {
  $Toast
} = require('../../dist/base/index');

Page({
  data: {
    url: '',
    placeholderText: '',
    joinType: '',
    groupId: ''
  },
  onLoad(options) {
    let data = JSON.parse(options.data)
    if (data.joinType == '0') {
      this.setData({
        placeholderText: '请输入组邀请码'
      })
    } else {
      this.setData({
        groupId: data.groupId,
        placeholderText: '请输入上级邀请码'
      })
    }
    this.setData({
      joinType: data.joinType
    })
  },
  handleChange(e) {
    this.setData({
      url: e.detail.detail.value
    })
  },
  joinGroup() {
    let that = this
    if (this.data.url == '') {
      $Toast({
        content: '请输入邀请码',
        image: '../../images/icon/despise.png'
      });
    } else {
      wx.cloud.callFunction({
        name: 'generateInviteCode',
        data: {
          type: 'decode',
          token: that.data.url
        }
      }).then(res => {
        if (res.result) {
          if (that.data.joinType == '0') { //加入组
            wx.cloud.callFunction({
              name: 'joinGroup',
              data: {
                groupId: res.result.groupId
              }
            }).then(res2 => {
              if (res2.result._id) {
                that.backUser()
              } else {
                $Toast({
                  content: '加入失败',
                  image: '../../images/icon/sad.png'
                });
              }
            })
          } else { //隶属上级
            if (res.result.groupId == that.data.groupId) {
              $Toast({
                content: '找自己干嘛',
                image: '../../images/icon/despise.png'
              });
              return
            }
            wx.cloud.callFunction({
              name: 'addLeader',
              data: {
                leaderId: res.result.groupId,
                groupId: that.data.groupId
              }
            }).then(res3 => {
              if (res3.result.stats) {
                that.backUser()
              } else {
                $Toast({
                  content: '加入失败',
                  image: '../../images/icon/sad.png'
                });
              }
            })
          }
        } else {
          $Toast({
            content: '邀请码错误或失效',
            image: '../../images/icon/sad.png'
          });
        }
      })
    }
  },
  backUser() {
    app.globalData.flushGroup = true
    app.globalData.flushView = true
    app.globalData.flushExport = true
    app.globalData.flushManage = true
    app.globalData.flushQrCode = true
    wx.switchTab({
      url: '/pages/user/user',
      success: function(res3) {
        wx.showToast({
          title: '加入成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  }
})